package org.nanhill.moo.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

/**
 * Controller for user register.
 * 
 * @author alin
 */
public abstract class NamedFormController extends SimpleFormController {
	private static final String SUBMIT_TYPE_KEY = "submitType";

	private String submitType;

	public void setSubmitType(String submitType) {
		this.submitType = submitType;
	}

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String type = request.getParameter(SUBMIT_TYPE_KEY);
		if (null == type || !type.equals(submitType)) {
			// create default empty model for page binding
			return showForm(request, response, this.getErrors(request));
		}
		return super.handleRequestInternal(request, response);
	}

	protected BindException getErrors(HttpServletRequest request)
			throws Exception {
		Object command = formBackingObject(request);
		ServletRequestDataBinder binder = createBinder(request, command);
		return new BindException(binder.getBindingResult());
	}

}